package com.bwsoft.portal.service.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.admin.domain.QualityControl;
import com.bwsoft.admin.domain.QualityControlJoiner;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.api.util.Constant;
import com.bwsoft.portal.domain.valueObject.QualityControlJoinerVO;
import com.bwsoft.portal.domain.valueObject.QualityControlListVO;
import com.bwsoft.portal.domain.valueObject.QualityControlVO;
import com.bwsoft.portal.service.QualityControlService;
import com.bwsoft.service.DictionaryDataService;
import com.bwsoft.util.Base64Util;
import com.bwsoft.util.DesUtil;
import com.bwsoft.util.UploadFileUtil;

@Service(QualityControlService.NAME)
public class QualityControlServiceImpl extends PortalBaseServiceImpl implements
		QualityControlService {
	private static Logger LOG = Logger.getLogger(QualityControlService.class
			.getClass());
	@Resource(name = DictionaryDataService.NAME)
	DictionaryDataService dictionaryDataService;

	@Override
	public List<QualityControl> findData(Integer page, Integer rows,
			String s_field, String s_scope, String s_count, String s_nature,
			String s_qcName, String showType, Integer accountId) {
		StringBuffer qualityCtrlHql = new StringBuffer();
		Map<String, String> statusMap = dictionaryDataService.getDicDataByName("qc_status");
		Map<String, String> fieldMap = dictionaryDataService.getDicDataByName("qc_field");
		Map<String, String> scopeMap = dictionaryDataService.getDicDataByName("qc_scope");
		Map<String, String> countMap = dictionaryDataService.getDicDataByName("qc_count");
		Map<String, String> natureMap = dictionaryDataService.getDicDataByName("qc_nature");
		qualityCtrlHql.append("from QualityControl as ctrl where 1=1");
		if (s_field != null && !"".equals(s_field.trim())) {
			qualityCtrlHql.append(" and ctrl.field=" + s_field.trim() + "");
		}
		if (s_scope != null && !"".equals(s_scope.trim())) {
			qualityCtrlHql.append(" and ctrl.scope=" + s_scope.trim() + "");
		}
		if (s_count != null && !"".equals(s_count.trim())) {
			qualityCtrlHql.append(" and ctrl.count=" + s_count.trim() + "");
		}
		if (s_nature != null && !"".equals(s_nature.trim())) {
			qualityCtrlHql.append(" and ctrl.nature =" + s_nature.trim() + "");
		}
		if (s_qcName != null && !"".equals(s_qcName.trim())) {
			qualityCtrlHql.append(" and ctrl.projectName like '%"
					+ s_qcName.trim() + "%'");
		}
		if (accountId != null && showType != null) {
			if ("2".equals(showType)) {
				qualityCtrlHql.append(" and ctrl.sponsor.accountId=" + accountId);
			} else if ("3".equals(showType)) {
				qualityCtrlHql.append(" and ctrl.qcId in (select qcjoiner.qualityControl.qcId " +
						"from QualityControlJoiner as qcjoiner where qcjoiner.joinerId=" + accountId + ")");
			} else if ("1".equals(showType)) {
				qualityCtrlHql.append(" and (ctrl.sponsor.accountId=" + accountId 
					+ " or ctrl.qcId in (select qcjoiner.qualityControl.qcId from QualityControlJoiner as qcjoiner " +
					"where qcjoiner.joinerId=" + accountId + "))");
			}
		} else {
			qualityCtrlHql.append(" and openFlag=1");
		}
		qualityCtrlHql.append(" order by ctrl.addTime desc");
		List<QualityControl> qualityControlData = qualityControlDao.findPage(
				qualityCtrlHql.toString(), rows, (page - 1) * rows);
		for (QualityControl qualityControl : qualityControlData) {
			qualityControl.setStatusName(statusMap.containsKey(qualityControl
					.getStatus().toString()) ? statusMap.get(qualityControl.getStatus().toString())
					: "");
			qualityControl.setFieldName(fieldMap.containsKey(qualityControl
							.getField().toString()) ? fieldMap.get(qualityControl
							.getField().toString()) : "");
			qualityControl.setScopeName(scopeMap.containsKey(qualityControl
							.getScope().toString()) ? scopeMap.get(qualityControl
							.getScope().toString()) : "");
			qualityControl.setCountName(countMap.containsKey(qualityControl
							.getCount().toString()) ? countMap.get(qualityControl
							.getCount().toString()) : "");
			qualityControl.setNatureName(natureMap.containsKey(qualityControl
					.getNature().toString()) ? natureMap.get(qualityControl.getNature().toString())
					: "");
		}
		return qualityControlData;
	}

	@Override
	public Long getTotalCount(String s_field, String s_scope, String s_count,
			String s_nature, String s_qcName, String showType, Integer accountId) throws Exception {
		StringBuffer qualityCtrlHql = new StringBuffer();
		qualityCtrlHql
				.append("select count(*) from QualityControl as ctrl where 1=1");
		if (s_field != null && !"".equals(s_field.trim())) {
			qualityCtrlHql.append(" and ctrl.field=" + s_field.trim() + "");
		}
		if (s_scope != null && !"".equals(s_scope.trim())) {
			qualityCtrlHql.append(" and ctrl.scope=" + s_scope.trim() + "");
		}
		if (s_count != null && !"".equals(s_count.trim())) {
			qualityCtrlHql.append(" and ctrl.count=" + s_count.trim() + "");
		}
		if (s_nature != null && !"".equals(s_nature.trim())) {
			qualityCtrlHql.append(" and ctrl.nature =" + s_nature.trim() + "");
		}
		if (s_qcName != null && !"".equals(s_qcName.trim())) {
			qualityCtrlHql.append(" and ctrl.projectName like '%"
					+ s_qcName.trim() + "%'");
		}
		if (accountId != null && showType != null) {
			if ("2".equals(showType)) {
				qualityCtrlHql.append(" and ctrl.sponsor.accountId=" + accountId);
			} else if ("3".equals(showType)) {
				qualityCtrlHql.append(" and ctrl.qcId in (select qcjoiner.qualityControl.qcId " +
						"from QualityControlJoiner as qcjoiner where qcjoiner.joinerId=" + accountId + ")");
			} else if ("1".equals(showType)) {
				qualityCtrlHql.append(" and (ctrl.sponsor.accountId=" + accountId 
					+ " or ctrl.qcId in (select qcjoiner.qualityControl.qcId from QualityControlJoiner as qcjoiner " +
					"where qcjoiner.joinerId=" + accountId + "))");
			}
		} else {
			qualityCtrlHql.append(" and openFlag=1");
		}
		Long count = (Long) qualityControlDao.findByHql(
				qualityCtrlHql.toString()).get(0);
		return count;
	}

	@Override
	public List<QualityControlListVO> getVo(List<QualityControl> qcs, Integer sponsor) {
		List<QualityControlListVO> qclistVo = new ArrayList<QualityControlListVO>();
		QualityControlListVO qcVo = new QualityControlListVO();
		for (QualityControl qc : qcs) {
			qcVo = new QualityControlListVO();
			qcVo.setBeginDate(qc.getBeginDate());
			qcVo.setCountName(qc.getCountName());
			qcVo.setDescription(qc.getDescription());
			qcVo.setFeedBackDate(qc.getFeedBackDate());
			qcVo.setFieldName(qc.getFieldName());
			qcVo.setNatureName(qc.getNatureName());
			qcVo.setProjectName(qc.getProjectName());
			qcVo.setQcId(qc.getQcId());
			qcVo.setScopeName(qc.getScopeName());
			qcVo.setStatusName(qc.getStatusName());
			qcVo.setOpenFlag(qc.getOpenFlag());
			boolean flag = false;
			for(QualityControlJoiner joiner : qc.getQualityControlJoiners()) {
				if (sponsor != null && sponsor.equals(joiner.getJoinerId().getAccountId())) {
					flag = true;
					break;
				}
			}
			qcVo.setMyQc(flag);
			qclistVo.add(qcVo);
		}
		return qclistVo;
	}

	@Override
	public ResponsePojo saveQualityCtrl(Account account, String projectName,
			String field, String scope, String count, String nature,
			String price, String standard, Date beginDate, Date feedBackDate,
			Date endDate, String description, String other, String ptclsj,
			String gbjgxx, String ptxz, File img1, String img1FileName,
			File img2, String img2FileName, File img3, String img3FileName) {
		QualityControl qualityCtrl = new QualityControl();
		ResponsePojo rp = new ResponsePojo();
		try {
			qualityCtrl.setAddTime(new Date());
			// ---------附件上传（如果没上传则取原数据库内容保存）--------------
			if (img1FileName != null && !"".equals(img1FileName)) {
				Calendar now = Calendar.getInstance();
				String stdFilepath = ServletActionContext.getServletContext()
						.getRealPath(
								Constant.PATH_IMG_QUALITYCONTROL + "/"
										+ now.get(Calendar.YEAR)
										+ (now.get(Calendar.MONTH) + 1));
				String newFileName = null;
				newFileName = UUID.randomUUID().toString()
						+ img1FileName.substring(img1FileName.lastIndexOf('.'),
								img1FileName.length()).toLowerCase();
				UploadFileUtil.uploadOneFile(newFileName, img1, stdFilepath);
				qualityCtrl.setImg1(Constant.PATH_IMG_QUALITYCONTROL + "/"
						+ now.get(Calendar.YEAR)
						+ (now.get(Calendar.MONTH) + 1) + "/" + newFileName);
			}
			if (img2FileName != null && !"".equals(img2FileName)) {
				Calendar now = Calendar.getInstance();
				String stdFilepath = ServletActionContext.getServletContext()
						.getRealPath(
								Constant.PATH_IMG_QUALITYCONTROL + "/"
										+ now.get(Calendar.YEAR)
										+ (now.get(Calendar.MONTH) + 1));
				String newFileName = null;
				newFileName = UUID.randomUUID().toString()
						+ img2FileName.substring(img2FileName.lastIndexOf('.'),
								img2FileName.length()).toLowerCase();
				UploadFileUtil.uploadOneFile(newFileName, img2, stdFilepath);
				qualityCtrl.setImg2(Constant.PATH_IMG_QUALITYCONTROL + "/"
						+ now.get(Calendar.YEAR)
						+ (now.get(Calendar.MONTH) + 1) + "/" + newFileName);
			}
			if (img3FileName != null && !"".equals(img3FileName)) {
				Calendar now = Calendar.getInstance();
				String stdFilepath = ServletActionContext.getServletContext()
						.getRealPath(
								Constant.PATH_IMG_QUALITYCONTROL + "/"
										+ now.get(Calendar.YEAR)
										+ (now.get(Calendar.MONTH) + 1));
				String newFileName = null;
				newFileName = UUID.randomUUID().toString()
						+ img3FileName.substring(img3FileName.lastIndexOf('.'),
								img3FileName.length()).toLowerCase();
				UploadFileUtil.uploadOneFile(newFileName, img3, stdFilepath);
				qualityCtrl.setImg3(Constant.PATH_IMG_QUALITYCONTROL + "/"
						+ now.get(Calendar.YEAR)
						+ (now.get(Calendar.MONTH) + 1) + "/" + newFileName);
			}
			qualityCtrl.setProjectName(projectName);
			qualityCtrl.setField(Integer.valueOf(field));
			qualityCtrl.setScope(Integer.valueOf(scope));
			qualityCtrl.setCount(Integer.valueOf(count));
			qualityCtrl.setNature(Integer.valueOf(nature));
			DecimalFormat df = new DecimalFormat("0.00");
			qualityCtrl.setPrice(df.format(new BigDecimal(price)));
			qualityCtrl.setStatus(1);
			qualityCtrl.setStandard(standard);
			qualityCtrl.setBeginDate(beginDate);
			qualityCtrl.setFeedBackDate(feedBackDate);
			qualityCtrl.setEndDate(endDate);
			qualityCtrl.setDescription(description);
			qualityCtrl.setOther(other);
			qualityCtrl.setPtclsj(ptclsj != null && "on".equals(ptclsj));
			qualityCtrl.setGbjgxx(gbjgxx != null && "on".equals(gbjgxx));
			qualityCtrl.setPtxz(ptxz != null && "on".equals(ptxz));
			qualityCtrl.setSponsor(account);
			qualityCtrl.setReportStatus(false);
			qualityCtrl.setOpenFlag(true);
			qualityControlDao.saveOrUpdate(qualityCtrl);
			rp.setErrcode(0);
			rp.setErrmsg("保存成功！");
		} catch (Exception e) {
			rp.setErrcode(15);
			rp.setErrmsg("保存失败");
			e.printStackTrace();
			LOG.info(e);
		}
		return rp;
	}

	@Override
	public boolean isImage(String imgType) {
		List<String> allowType = Arrays.asList(".bmp", ".png", ".gif", ".jpg",
				".jpeg", ".pjpeg");
		return allowType.contains(imgType);
	}

	@Override
	public QualityControl findById(Integer qualityId) {
		QualityControl qualityControl = qualityControlDao.findById(qualityId);
		qualityControl.setStatusName(dictionaryDataService.getDicValueDataByNameValue("qc_status", qualityControl.getStatus()));
		qualityControl.setFieldName(dictionaryDataService.getDicValueDataByNameValue("qc_field", qualityControl.getField()));
		qualityControl.setScopeName(dictionaryDataService.getDicValueDataByNameValue("qc_scope", qualityControl.getScope()));
		qualityControl.setCountName(dictionaryDataService.getDicValueDataByNameValue("qc_count", qualityControl.getCount()));
		qualityControl.setNatureName(dictionaryDataService.getDicValueDataByNameValue("qc_nature", qualityControl.getNature()));
		return qualityControl;
	}

	@Override
	public QualityControlVO getVo(QualityControl qc) throws Exception {
		QualityControlVO qcVo = new QualityControlVO();
		qcVo.setSponsorId(qc.getSponsor().getAccountId());
		qcVo.setBeginDate(qc.getBeginDate());
		qcVo.setCountName(qc.getCountName());
		qcVo.setDescription(qc.getDescription());
		qcVo.setFeedBackDate(qc.getFeedBackDate());
		qcVo.setFieldName(qc.getFieldName());
		qcVo.setNatureName(qc.getNatureName());
		qcVo.setProjectName(qc.getProjectName());
		qcVo.setQcId(qc.getQcId());
		qcVo.setScopeName(qc.getScopeName());
		qcVo.setStatusName(qc.getStatusName());
		qcVo.setQualityControlJoinersLength(qc.getQualityControlJoiners()
				.size());
		qcVo.setEndDate(qc.getEndDate());
		qcVo.setStandard(qc.getStandard());
		qcVo.setSponsorCompName(qc.getSponsor().getCompName());
		qcVo.setPrice(qc.getPrice());
		qcVo.setOpenFlag(qc.getOpenFlag());
		qcVo.setOther(qc.getOther());
		qcVo.setImg1(qc.getImg1());
		qcVo.setImg2(qc.getImg2());
		qcVo.setImg3(qc.getImg3());
		qcVo.setReportStatus(qc.getReportStatus());
		qcVo.setCloseReason(qc.getCloseReason());
		qcVo.setGbjgxx(qc.getGbjgxx());
		com.bwsoft.admin.domain.File f = qc.getFile();
		if (f != null) {
			qcVo.setFilePath("api/jsp/pdf.jsp?r="+Base64Util.getBase64(DesUtil.encrypt("fileid="+qc.getFile().getId(), Constant.KEY_DES).getBytes("utf-8")));
		}
		return qcVo;
	}

	@Override
	public Long getUserCountTotalCount(Integer qualityId) {
		return (Long)qualityControlDao.findByHql("select count(*) from QualityControlJoiner as q " +
				"where q.qualityControl.qcId=?", qualityId).get(0);
	}

	@Override
	public List<QualityControlJoiner> findUserCountData(Integer page, Integer rows, Integer qualityId) {
		List<QualityControlJoiner> joinerList = qualityControlDao.findPage("from QualityControlJoiner as q " +
				"where q.qualityControl.qcId=?", rows, (page - 1) * rows, qualityId);
		return joinerList;
	}

	@Override
	public List<QualityControlJoinerVO> getJoinerVo(List<QualityControlJoiner> qcList) {
		List<QualityControlJoinerVO> qcjVoList = new ArrayList<QualityControlJoinerVO>();
		QualityControlJoinerVO qcjVo;
		Map<String, String> natureMap = dictionaryDataService.getDicDataByName("comp_nature");
		for (QualityControlJoiner joiner : qcList) {
			qcjVo = new QualityControlJoinerVO();
			qcjVo.setJoinerIdCompName(joiner.getJoinerId().getCompName());
			Integer i=joiner.getJoinerId().getAccountId();
			System.out.println(joiner.getJoinerId().getAccountId());
			qcjVo.setJoinerIdNatureName(natureMap.containsKey(joiner.getJoinerId().getCompNature().toString()) 
					? natureMap.get(joiner.getJoinerId().getCompNature().toString()) : "");
			qcjVo.setJoinerIdEmail(joiner.getJoinerId().getEmail());
			qcjVo.setJoinerIdLinkMan(joiner.getJoinerId().getLinkMan());
			qcjVo.setJoinerIdPhone(joiner.getJoinerId().getPhone());
			qcjVoList.add(qcjVo);
		}
		return qcjVoList;
	}

	@Override
	public ResponsePojo signup(Account account, Integer qualityId) {
		ResponsePojo rp = new ResponsePojo();
		try {
			QualityControl qc = qualityControlDao.findById(qualityId);
			if (qc != null && account != null && account.getAccountType() == 2) {
				List<QualityControlJoiner> joinerExist = qualityControlJoinerDao.findByHql("from QualityControlJoiner q " +
						"where q.qualityControl.qcId=? and q.joinerId.accountId=?", qualityId, account.getAccountId());
				if (joinerExist.size() > 0) {
					rp.setErrcode(1);
					rp.setErrmsg("您已经报名了，请勿重复报名");
				} else {
					QualityControlJoiner joiner = new QualityControlJoiner();
					joiner.setJoinerId(account);
					joiner.setQualityControl(qc);
					joiner.setAddTime(new Date());
					qualityControlJoinerDao.save(joiner);
					rp.setErrcode(0);
					rp.setErrmsg("报名成功！");
				}
			} else {
				rp.setErrcode(2);
				rp.setErrmsg("报名失败！");
			}
		} catch (Exception e) {
			rp.setErrcode(2);
			rp.setErrmsg("报名失败！");
			e.printStackTrace();
		} 
		
		return rp;
	}

}
